package com.bw.common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.common.base.BaseActivity
import com.bw.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviActivity<T:ViewDataBinding>:BaseActivity<T>(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        updateUI()
        //注册 EventBus
        EventBus.getDefault().register(this)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event:CustomEvent){
        if(event!= null && event.target==this::class.java.simpleName){
            handEvent(event)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        //取消注册 EventBus
        EventBus.getDefault().unregister(this)
    }


    private fun initData() {
        lifecycleScope.launch {
            sendViewIntent()
        }
    }
    //子类可以选择性的重写该方法


    private fun updateUI(){
        //监听生命周期 协程作用域 具备生命周期感知
        lifecycleScope.launch {
            //指定在Activity 执行某一个生命周期时 启动这个协程
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }
    open suspend fun sendViewIntent(){}

    open suspend fun collectUIState(){
    }

    open fun handEvent(event: CustomEvent){
    }
}